package com.emily.test.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.*;
import com.emily.test.service.*;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.DateUtil;
import com.emily.test.utils.MD5Utils;
import com.emily.test.vo.CompanyVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.util.*;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(value = "TCompanyController")
@Api(value = "TCompanyControllerApi", description = "公司管理接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class TCompanyController {

    private Logger logger = LoggerFactory.getLogger(ShardingGroupController.class);

    @Autowired
    private TCompanyService tCompanyService;
    @Autowired
    private TUserService tUserService;
    @Autowired
    private TUserRoleService tUserRoleService;
    @Autowired
    private RCompanyRoleService rCompanyRoleService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private TRoleMenuService tRoleMenuService;
    @Autowired
    private TCompanyResourceService tCompanyResourceService;
    @Autowired
    private TResourceService tResourceService;
    @Autowired
    private TMenuService tMenuService;

    @ApiOperation(value = "根据ID获取公司具体信息", notes = "TCompany")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司ID", required = true)
    })
    @PostMapping(value = "selectCompanyInfoById")
    public ResponseResult selectCompanyInfoById(@RequestBody JSONObject jsonObject) {
        int id = jsonObject.getInteger("id");
        try {
            CompanyVO companyVO = tCompanyService.selectCompanyInfoById(id);
            logger.info("根据ID查询公司具体信息={}", companyVO);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS, companyVO);
        } catch (Exception e) {
            logger.error("根据ID查询公司具体信息异常:{}", e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    @ApiOperation(value = "增加一条公司信息", notes = "目前废弃")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "cName", value = "公司名称", required = true),
            @ApiImplicitParam(name = "companyCode", value = "公司代码", required = true),
            @ApiImplicitParam(name = "state", value = "是否启用"),
            @ApiImplicitParam(name = "description", value = "备注")
    })
    @PostMapping(value = "insertTCompanyInfo")
    public ResponseResult insertTCompanyInfo(@RequestBody JSONObject jsonObject) {
        try {
            TCompany tCompany = (TCompany) ConstentUtil.json2Object(jsonObject, TCompany.class);
            // int num = tCompanyService.insertTCompanyInfo(tCompany);
            tCompany.getClass();
            int num = 0;
            if (num == 0) {
                logger.error("添加公司信息失败,添加条数={}", num);
                return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
            }
            logger.info("添加公司信息成功,tCompany={}", tCompany);
            return ResponseResult.success(num);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加公司信息异常,异常信息：{}", e);
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }

    @ApiOperation(value = "修改公司的其中某些信息", notes = "TCompany")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司ID", required = true),
            @ApiImplicitParam(name = "cName", value = "公司名称"),
            @ApiImplicitParam(name = "companyCode", value = "公司代码"),
            @ApiImplicitParam(name = "legalPerson", value = "公司法人"),
            @ApiImplicitParam(name = "state", value = "是否启用"),
            @ApiImplicitParam(name = "email", value = "公司邮箱"),
            @ApiImplicitParam(name = "phone", value = "法人电话")
    })
    @PostMapping(value = "updateSomeTCompanyInfo")
    public ResponseResult updateSomeTCompanyInfo(@RequestBody JSONObject jsonObject) {
        try {
            CompanyVO companyVO = (CompanyVO) ConstentUtil.json2Object(jsonObject, CompanyVO.class);
            TUser tUser = tUserService.findUsertByCode(companyVO.getCompanyCode());
            String time = DateUtil.getNowStr();
            tUser.setUpdateTime(time);
            tUser.setLoginName(companyVO.getEmail());
            tUser.setUserName(companyVO.getCName() + "管理");
            tUserService.updateUserInfoByUserId(tUser);
            int num = tCompanyService.updateTCompany(companyVO);
            logger.info("修改公司的信息成功");
            return ResponseResult.success(ReturnValueConstants.UPDATE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改公司的信息异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    /**
     * 根据ID删除公司信息
     *
     * @param jsonObject
     * @return
     */
    @ApiOperation(value = "根据ID删除公司信息", notes = "TCompany")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司ID", required = true)
    })
    @PostMapping(value = "deleteTCompanyById")
    public ResponseResult deleteTCompanyById(@RequestBody JSONObject jsonObject) {
        try {

            int id = jsonObject.getInteger("id");
            //将所选的公司信息进行逻辑删除:state状态改为2
            TCompany tCompany = new TCompany();
            tCompany.setId(id);
            tCompany.setState(2);
            tCompany.setUpdateTime(DateUtil.getNowStr());
            int num = tCompanyService.updateTCompany(tCompany);
            logger.info("根据ID删除公司信息成功,companyId={}" + id);
            return ResponseResult.success(ReturnValueConstants.DELATE_SUCCESS, num);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除公司信息异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.DELATE_FAILURE);
        }
    }


    @ApiOperation(value = "查询公司信息列表", notes = "TCompany")
    @PostMapping(value = "selectTCompanyList")
    public ResponseResult selectTCompanyList() {
        try {
            List<CompanyVO> companyVOList1 = tCompanyService.getCompanyList();
            // List<CompanyVO> companyVOList1= new ArrayList<>();
            logger.info("查询公司信息列表成功!={}", companyVOList1);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS, companyVOList1);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询公司信息列表异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }


    @ApiOperation(value = "查询仍未配置角色的公司信息列表", notes = "TCompany")
    @PostMapping(value = "getCompanyListNoRoles")
    public ResponseResult getCompanyListNoRoles() {
        try {
            List<TCompany> resourceList = tCompanyService.getCompanyListNoRoles();
            logger.info("查询公司信息列表成功!resourceList={}", resourceList);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS, resourceList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询公司信息列表异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    @ApiOperation(value = "根据条件查询公司信息列表", notes = "TCompany")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "公司id"),
            @ApiImplicitParam(name = "cName", value = "公司名称"),
            @ApiImplicitParam(name = "companyCode", value = "公司代码"),
            @ApiImplicitParam(name = "description", value = "备注"),
            @ApiImplicitParam(name = "state", value = "是否启用"),
    })
    @PostMapping(value = "selectTCompanyListByCondition")
    public ResponseResult selectTCompanyListByCondition(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        String cName = jsonObject.getString("cName");
        String companyCode = jsonObject.getString("companyCode");
        String description = jsonObject.getString("description");
        String updateTime = jsonObject.getString("updateTime");
        TCompany tCompany = new TCompany();
        tCompany.setId(id);
        tCompany.setcName(cName);
        tCompany.setCompanyCode(companyCode);
        tCompany.setDescription(description);
        tCompany.setUpdateTime(updateTime);
        try {
            List<TCompany> resourceList = tCompanyService.getCompanyList(tCompany);
            logger.info("根据条件查询公司信息列表成功!resourceList={}", resourceList);
            return ResponseResult.success(ReturnValueConstants.QUERY_SUCCESS, resourceList);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据条件查询公司信息列表异常:{}", e);
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 禁用多个公司
     *
     * @param jsonObject 其中公司ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value = "禁用多个公司信息", notes = "根据id禁用公司信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "公司ID列表", required = true)
    })
    @PostMapping(value = "disabledCompanyById")
    public ResponseResult disabledCompanyById(@RequestBody JSONObject jsonObject) {
        String ids = jsonObject.getString("ids").replaceAll("\\[", "").replaceAll("]", "");
        String[] idStr = ids.split(",");
        List<TCompany> tCompanyList = new ArrayList<TCompany>();
        if (idStr.length != 0) {
            for (int i = 0; i < idStr.length; i++) {
                TCompany tCompany = new TCompany();
                tCompany.setId(ConstentUtil.strToInteger(idStr[i]));
                tCompany.setState(0);
                tCompanyList.add(tCompany);
            }
        }
        try {
            int num = tCompanyService.updateTCompanyById(tCompanyList);
            logger.info("ids为{}的公司已禁用", ids);
            return ResponseResult.success("0", "禁用成功", tCompanyList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("禁用失败");
        }
    }

    /**
     * 启用多个公司
     *
     * @param jsonObject 其中角色ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value = "启用多个公司信息", notes = "根据id启用公司信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "公司ID列表", required = true)
    })
    @PostMapping(value = "enabledCompanyById")
    public ResponseResult enabledCompanyById(@RequestBody JSONObject jsonObject) {
        String ids = jsonObject.getString("ids").replaceAll("\\[", "").replaceAll("]", "");
        String[] idStr = ids.split(",");
        List<TCompany> tCompanyList = new ArrayList<TCompany>();
        if (idStr.length != 0) {
            for (int i = 0; i < idStr.length; i++) {
                TCompany tCompany = new TCompany();
                tCompany.setId(ConstentUtil.strToInteger(idStr[i]));
                tCompany.setState(1);
                tCompany.setUpdateTime(DateUtil.getNowStr());
                tCompanyList.add(tCompany);
            }
        }
        try {
            tCompanyService.updateTCompanyById(tCompanyList);
            logger.info("ids为{}的公司已启用", ids);
            return ResponseResult.success("0", "启用成功", tCompanyList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("启用失败");
        }
    }

    /**
     * 删除多个公司（假删除，state=2）
     *
     * @param jsonObject 其中角色ids的格式为:{1,2,3,4}
     * @return
     */
    @ApiOperation(value = "删除多个公司信息", notes = "根据id删除公司信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "公司ID列表", required = true)
    })
    @PostMapping(value = "deleteCompanyById")
    public ResponseResult deleteCompanyById(@RequestBody JSONObject jsonObject) {
        String ids = jsonObject.getString("ids").replaceAll("\\[", "").replaceAll("]", "");
        String[] idStr = ids.split(",");
        List<TCompany> tCompanyList = new ArrayList<TCompany>();
        if (idStr.length != 0) {
            for (int i = 0; i < idStr.length; i++) {
                TCompany tCompany = new TCompany();
                tCompany.setId(ConstentUtil.strToInteger(idStr[i]));
                tCompany.setState(2);
                tCompany.setUpdateTime(DateUtil.getNowStr());
                tCompanyList.add(tCompany);
            }
        }
        try {
            tCompanyService.updateTCompanyById(tCompanyList);
            logger.info("ids为{}的公司已删除", ids);
            return ResponseResult.success("0", "删除成功", tCompanyList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("删除失败");
        }
    }

    @ApiOperation(value = "注册公司信息", notes = "TCompany")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "cName", value = "公司名称", required = true),
            @ApiImplicitParam(name = "companyCode", value = "公司代码", required = true),
            @ApiImplicitParam(name = "email", value = "企业邮箱"),
            @ApiImplicitParam(name = "password", value = "管理密码"),
            @ApiImplicitParam(name = "legalPerson", value = "法人"),
            @ApiImplicitParam(name = "phone", value = "法人电话")
    })
    @PostMapping(value = "addTCompanyInfo")
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ResponseResult addTCompanyInfo(@RequestBody JSONObject jsonObject) {
        try {
            logger.error("获取公司信息={}", jsonObject.toString());
            CompanyVO companyVO = (CompanyVO) ConstentUtil.json2Object(jsonObject, CompanyVO.class);
            int companyNum = tCompanyService.insertTCompanyInfo(companyVO);
            if (companyNum == 0) {
                logger.error("添加公司信息失败,公司code已存在");
                return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
            }
            logger.info("1、公司管理员信息初始化...");
            TUser tUser = new TUser();
            String time = DateUtil.getNowStr();
            tUser.setLoginName(companyVO.getEmail());
            tUser.setPassword(MD5Utils.getEncryptedPwd(companyVO.getPassword()));
            tUser.setUserName(companyVO.getCName() + "管理");
            tUser.setCompanyCode(companyVO.getCompanyCode());
            tUser.setCreateTime(time);
            tUser.setUpdateTime(time);
            tUser.setCompanyName(companyVO.getCName());
            tUser.setPhone(companyVO.getPhone());
            int userNum = tUserService.insertUser(tUser);
            logger.info("2、公司管理员角色初始化...");
            TRole role = new TRole();
            role.setrName("管理员");
            role.setrCode(companyVO.getCompanyCode() + "admin");
            role.setUpdateTime(time);
            role.setDescription(companyVO.getCName() + "管理员");
            role.setState(1);
            roleService.insertRole(role);
            logger.info("3、管理员-角色初始化...");
            Map<String, Object> map = new HashMap<>(2);
            List<String> list = new ArrayList<>();
            map.put("userId", tUser.getId());
            list.add(role.getId().toString());
            map.put("roleIds", list);
            tUserRoleService.insertTUserRoleInfo(map);
            logger.info("4、公司-角色初始化...");
            RCompanyRole rCompanyRole = new RCompanyRole();
            TCompany t = tCompanyService.getCompanyByCode(companyVO.getCompanyCode());
            rCompanyRole.setCompanyId(t.getId());
            rCompanyRole.setRoleId(role.getId());
            rCompanyRoleService.insert(rCompanyRole);
            logger.info("5、公司-资源初始化...");
            TResource tResource = new TResource();
            tResource.setResName("平台维护管理系统");
            List<TResource> resources = tResourceService.selectResourceListByCondition(tResource);
            TCompanyResource tCompanyResource = new TCompanyResource();
            tCompanyResource.setCompanyId(t.getId());
            tCompanyResource.setResourceId(resources.get(0).getId());
            tCompanyResourceService.insert(tCompanyResource);
            logger.info("6、管理员角色-菜单初始化...");
            TMenu tMenu = new TMenu();
            tMenu.setResourceId(tCompanyResource.getResourceId());
            List<TMenu> tMenuList = tMenuService.getMenuInfoListByCondition(tMenu);
            String[] rName = {"角色管理", "用户-角色管理", "用户管理", "部门管理"};
            for (TMenu tMenu1 : tMenuList) {
                if (Arrays.asList(rName).contains(tMenu1.getMenuName())) {
                    TRoleMenu tRoleMenu = new TRoleMenu();
                    tRoleMenu.setMenuId(tMenu1.getId());
                    tRoleMenu.setRoleId(role.getId());
                    tRoleMenuService.insert(tRoleMenu);
                }
            }
            logger.info("======初始化完成======");
            if (userNum == 0 && companyNum == 0) {
                logger.error("添加公司信息失败");
                return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
            }
            logger.info("添加公司信息成功");
            return ResponseResult.success(ReturnValueConstants.ADD_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加公司信息异常,异常信息：{}", e);
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }
}
